import React, { PureComponent } from 'react'
import {
 Button, Popconfirm, Select, Tooltip,
} from 'antd'
import {
 BreadcrumbBar, InputSearch, ProTable, ProTableOperate, ProTableOptions,
} from '@/components'
import { deleteDataSourceById, getLastUpdateTime } from './api'
import { getHashParameterByName } from '@/utils/helper'
import DataSource from './dataSource'
import styles from './index.less'

const { Option } = Select
const { OperateItem } = ProTableOperate
const menus = [{ name: '数据调研' }, { name: '数据管理' }]
export default class DataManager extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      query: {
        status: getHashParameterByName('status') ? Number(getHashParameterByName('status')) : '',
      },
      status: getHashParameterByName('status') ? Number(getHashParameterByName('status')) : '',
      index: null,
      id: null,
      dsType: '',
      dsName: '',
      dataSourceIsEdit: false,
      dataSourceIsCheck: false,
      dsTypes: [{
        name: 'Hive',
        id: 'Hive',
      }, {
        name: 'PostgreSQL',
        id: 'PostgreSQL',
      }, {
        name: 'MySQL',
        id: 'MySQL',
      }, {
        name: 'SQL Server',
        id: 'SQLServer',
      }, {
        name: 'DB2',
        id: 'DB2',
      }, {
        name: 'Oracle',
        id: 'Oracle',
      }, {
        name: 'Sap Hana',
        id: 'Sap',
      }, {
        name: '人大金仓',
        id: 'KINGBASE8',
      }, {
        name: '达梦',
        id: 'DM',
      }, {
        name: 'MaxCompute',
        id: 'MaxCompute',
      }, {
        name: 'HBase',
        id: 'HBase',
      }, {
        name: 'Mongodb',
        id: 'Mongodb',
      }, {
        name: 'HDFS',
        id: 'HDFS',
      }, {
        name: 'Open TSDB',
        id: 'OpenTSDB',
      }, {
        name: 'Kafka',
        id: 'Kafka',
      }, {
        name: 'MQTT',
        id: 'MQTT',
      }, {
        name: 'Dgraph',
        id: 'Dgraph',
      }, {
        name: 'TiDB',
        id: 'TiDB',
      }, {
        name: 'IoTDB',
        id: 'IoTDB',
      }, {
        name: 'AS400',
        id: 'AS400',
      }, {
        name: 'InfluxDB',
        id: 'InfluxDB',
      }],
    }
    this.addDataSourceRef = React.createRef()
    this.editDataSourceRef = React.createRef()
    this.seeDataSourceRef = React.createRef()
    this.tableRef = React.createRef()
  }

  componentDidMount() {
    this.getLastUpdateTime()
  }

  getLastUpdateTime = () => {
    getLastUpdateTime().then((res) => {
      this.setState({
        updateTime: res.data,
      })
    })
  }

  clearIndex = () => {
    this.setState({
      index: null,
    })
  }

  dataSourceModal = () => {
    this.setState({
      index: null,
    }, () => {
      this.setState({
        dataSourceIsEdit: false,
        dataSourceIsCheck: false,
        index: 0,
      }, () => {
        this.addDataSourceRef.current.openModal()
      })
    })
  }

  editDataSourceModal = (id) => {
    this.setState({
      id,
      index: null,
    }, () => {
      this.setState({
        dataSourceIsEdit: false,
        dataSourceIsCheck: false,
        index: 1,
      }, () => {
        this.editDataSourceRef.current.openModal()
      })
    })
  }

  seeDataSourceModal = (id) => {
    this.setState({
      id,
      index: null,
    }, () => {
      this.setState({
        dataSourceIsEdit: true,
        dataSourceIsCheck: true,
        index: 2,
      }, () => {
        this.seeDataSourceRef.current.openModal()
      })
    })
  }

  deleteStorageFn = (id) => {
    this.setState({
      visibleDele: true,
    })
    deleteDataSourceById({ id }).then((data) => {
      const { dsType, dsName } = this.state
      this.tableRef?.current?.resetPageNum()
      this.setState({
        visibleDele: false,
        query: {
          dsName,
          dsType,
        },
      })
    })
  }

  clearTable = () => {
    const { dsType, dsName } = this.state
    this.tableRef?.current?.resetPageNum()
    this.setState({
      query: {
        dsType,
        dsName,
      },
    })
  }

  render() {
    const {
      dataSourceIsEdit,
      dataSourceIsCheck,
      dsTypes,
      index,
      query,
      id,
      updateTime,
    } = this.state
    const model = [
      <DataSource
        id={null}
        title="新建数据源"
        dsTypes={dsTypes}
        clearTable={this.clearTable}
        clearIndex={this.clearIndex}
        ref={this.addDataSourceRef}
        isEdit={dataSourceIsEdit}
        isCheck={dataSourceIsCheck}
        index={index}
      />,
      <DataSource
        id={id}
        title="编辑数据源"
        dsTypes={dsTypes}
        clearTable={this.clearTable}
        clearIndex={this.clearIndex}
        ref={this.editDataSourceRef}
        isEdit={dataSourceIsEdit}
        isCheck={dataSourceIsCheck}
        index={index}
      />,
      <DataSource
        id={id}
        title="查看数据源"
        dsTypes={dsTypes}
        clearTable={this.clearTable}
        clearIndex={this.clearIndex}
        ref={this.seeDataSourceRef}
        isEdit={dataSourceIsEdit}
        isCheck={dataSourceIsCheck}
      />]
    return (
      <div className={styles.page_content_with_breadcrumb}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.page_content}>
          <div className={styles.page_content_right}>
            <ProTableOperate
              toggleOperate={false} // 是否隐藏 收起/展开 按钮 (如果隐藏按钮，handleToggleSta设置属性值不生效)
              unfolded // 默认展开状态
            >
              <OperateItem align="left">
                数据源类型
                <Select
                  allowClear
                  placeholder="请选择数据源类型"
                  onChange={(dsType) => {
                    this.tableRef?.current?.resetPageNum()
                    const { status, dsName } = this.state
                    this.setState({
                      dsType,
                      query: {
                        dsType: dsType || '',
                        dsName: dsName || '',
                        status: status || status === 0 ? status : '',
                      },
                    })
                  }}
                >
                  {dsTypes && dsTypes.map((obj) => (
                    <Option
                      value={obj.id}
                      key={obj.id}
                    >
                      {obj.name}
                    </Option>
                  ))}
                </Select>
              </OperateItem>
              <OperateItem align="left">
                连接状态
                <Select
                  allowClear
                  placeholder="请选择连接状态"
                  value={this.state.status}
                  onChange={(status) => {
                    this.tableRef?.current?.resetPageNum()
                    const { dsName, dsType } = this.state
                    this.setState({
                      status,
                      query: {
                        dsType: dsType || '',
                        dsName: dsName || '',
                        status: status || status === 0 ? status : '',
                      },
                    })
                  }}
                >
                  <Option value={0}>失败</Option>
                  <Option value={1}>成功</Option>
                </Select>
              </OperateItem>
              <OperateItem align="left">
                <InputSearch
                  placeholder="请输入数据源进行搜索"
                  value={this.state.dsName}
                  onChange={(e) => {
                    this.setState({
                      dsName: e.target.value,
                    })
                  }}
                  onSearch={() => {
                    const { dsType, dsName, status } = this.state
                    this.tableRef?.current?.resetPageNum()
                    this.setState({
                      query: {
                        dsType: dsType || '',
                        dsName: dsName || '',
                        status: status || status === 0 ? status : '',
                      },
                    })
                  }}
                />
              </OperateItem>
              <OperateItem itemType="btn">
                {
                  [
                    <Button type="link" className={styles.button_updateTime}>
                      <Tooltip
                        placement="topRight"
                        title={
                          <p>连接状态1小时监测一次</p>
                        }
                      ><i className="iconfont icon-shijian" />
                      </Tooltip>
                      最近更新时间：{updateTime}
                    </Button>,
                    <Button
                      type="primary"
                      onClick={this.dataSourceModal}
                      key="new"
                    >
                      新增数据源
                    </Button>,
                  ]
                }
              </OperateItem>
            </ProTableOperate>
            <ProTable
              query={query}
              rowKey="id"
              url="/api/v1/normalization/datasource/getDSPageList"
              columns={[
                {
                  title: '数据源名称',
                  dataIndex: 'dsName',
                  width: '10%',
                  key: 'dsName',
                },
                {
                  title: '数据源类型',
                  dataIndex: 'dsType',
                  width: '10%',
                  key: 'dsType',
                },
                {
                  title: '连接信息',
                  dataIndex: 'dsLink',
                  width: '20%',
                  key: 'dsLink',
                },
                {
                  title: '数据源描述',
                  dataIndex: 'dsDesc',
                  width: '20%',
                  key: 'dsDesc',
                  render: (text, record) => (!text || text === '' ? '--' : text),
                },
                {
                  title: '最近修改时间 ',
                  dataIndex: 'updateTime',
                  width: '10%',
                  key: 'updateTime',
                },
                {
                  title: '连接状态 ',
                  dataIndex: 'status',
                  width: '15%',
                  key: 'status',
                  render: (status) => (
                    [
                      <>
                        <i className="iconfont icon-shibai1 hu-red" />
                        失败
                      </>,
                      <>
                        <i className="iconfont icon-chenggong hu-green" />
                        成功
                      </>,
                    ][status]

                  ),
                },
                {
                  title: '操作',
                  dataIndex: 'operation',
                  width: '15%',
                  key: 'operation',
                  render: (text, record) => (
                    <ProTableOptions>
                      <span
                        key="check"
                        onClick={() => {
                          this.seeDataSourceModal(record.id)
                        }}
                      >
                        查看
                      </span>
                      {
                        !record.isSystem ? (
                          <span
                            key="edit"
                            onClick={() => {
                              this.editDataSourceModal(record.id)
                            }}
                          >
                            编辑
                          </span>
                        ) : null
                      }
                      {
                        !record.isSystem ? (
                          <Popconfirm
                            title="确定要删除吗？"
                            onConfirm={() => { this.deleteStorageFn(record.id) }}
                            visible={this.state.visibleDele === record.id}
                            onCancel={() => { this.setState({ visibleDele: false }) }}
                            okText="是"
                            cancelText="否"
                            key="del"
                          >
                            <span onClick={() => { this.setState({ visibleDele: record.id }) }}>
                              删除
                            </span>
                          </Popconfirm>
                        ) : null
                      }
                    </ProTableOptions>
                  ),
                },
              ]}
              ref={this.tableRef}
              loading={false}
            />
            {model[index]}
          </div>
        </div>
      </div>
    )
  }
}
